﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace SmartMathLibrary.Space
{
    /// <summary>
    /// This class provides clone functions to clone object instances.
    /// </summary>
    [Serializable]
    public static class CloneFunctions
    {
        /// <summary>
        /// Supports cloning, which creates a new instance of a class with the same value as an existing instance.
        /// </summary>
        /// <param name="source">The source object instance.</param>
        /// <returns>A deep copy of the source object instance.</returns>
        public static object Clone(Object source)
        {
            if (!typeof (Object).IsSerializable)
            {
                throw new ArgumentException("The type must be serializable.", "source");
            }

            if (Object.ReferenceEquals(source, null))
            {
                return default(Object);
            }

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new MemoryStream();

            using (stream)
            {
                formatter.Serialize(stream, source);
                stream.Seek(0, SeekOrigin.Begin);

                return formatter.Deserialize(stream);
            }
        }
    }
}